package com.fafu.service.Impl;

import com.fafu.dao.mapper.*;
import com.fafu.model.*;
import com.fafu.pojo.MessageAndPics;
import com.fafu.pojo.OtherSearchHORList;
import com.fafu.pojo.RefusePojo;
import com.fafu.service.OtherService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import util.Dictionary;
import util.Dictionary.REPAIR;
import util.JsonRsp;
import util.MyMap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static util.Dictionary.CODE.RECORD_NOT_EXITS;
import static util.Dictionary.CODE.SUCCESS;
import static util.Dictionary.CODE.TYPE_ERROR;
import static util.Dictionary.REPAIR.*;

@Service
public class OtherServiceImpl implements OtherService {
    @Autowired
    private StudentrepairMapper studentrepairMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private ManagerMapper managerMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private ImageMapper imageMapper;
    @Autowired
    private OtherquestionMapper otherquestionMapper;

    @Override
    public Map<String, Object> searchRefuseList(Map<String, Object> paramMap) {
        Integer operationId = (Integer) paramMap.get("operationId");
        Manager manager = managerMapper.selectByPrimaryKey(operationId);
        Integer area = manager.getArea();
        paramMap.put("area",area);
        PageHelper.startPage((Integer)paramMap.get("pageNum"),(Integer)paramMap.get("pageSize"));
        List<RefusePojo> refusePojos = messageMapper.searchRefuseList(paramMap);
        PageInfo pageInfo = new PageInfo(refusePojos);
        return new MyMap().put("data",pageInfo.getList()).put("count",pageInfo.getTotal()).toMap();
    }

    @Override
    public Map<String, Object> addMessage(Map<String, Object> paramMap) {
        /**
         *如果area为空，为管理员报修。。添加area = manager,area
         * 不为空
         *     直接添加: 插入获取id用于图片添加字段
         */
        MessageAndPics messageAndPics = (MessageAndPics) paramMap.get("data");
        if(messageAndPics.getArea() == null){
            Integer oId = messageAndPics.getOperationManager();
            Manager manager = managerMapper.selectByPrimaryKey(oId);
            if(manager != null){
                messageAndPics.setArea(manager.getArea());
            }
        }
        messageMapper.inserAndGetId(messageAndPics);
        List<String>pics = messageAndPics.getPics();
        if(pics != null) {
            for (String pic : pics) {
                Image image = imageMapper.selectByPrimaryKey(pic);
                image.setRepairid(messageAndPics.getId());
                image.setTableIden(Dictionary.TABLE.TABLE_OTHER_QUESTION);
                imageMapper.updateByPrimaryKey(image);
            }
        }
        return new MyMap().put("code",SUCCESS).put("data",messageAndPics.getId()).toMap();
    }

    @Override
    public Map<String, Object> searchItemAndPics(Map<String, Object> map) {
        Message message = messageMapper.selectByPrimaryKey((Integer)map.get("id"));
        MessageAndPics messageAndPics = new MessageAndPics();
        if(message == null)
            return new MyMap()
                    .put("code", Dictionary.CODE.RECORD_NOT_EXITS)
                    .put("msg","record is not exist").toMap();

        BeanUtils.copyProperties(message,messageAndPics);
        List<String> imageUrls = new ArrayList<>();
        Example example = new Example(Image.class);
        example.or().andEqualTo("tableIden", Dictionary.TABLE.TABLE_OTHER_QUESTION)
        .andEqualTo("repairid",(Integer)map.get("id"));
        List<Image> images = imageMapper.selectByExample(example);
        for(Image image: images)
            imageUrls.add(image.getUrl());
        messageAndPics.setPics(imageUrls);
        return new MyMap().put("data",messageAndPics).put("code", Dictionary.CODE.SUCCESS).toMap();
    }

    @Override
    public Map<String, Object> refuse(Map<String, Object> map) {
        Integer id = (Integer) map.get("id");
        Message message = messageMapper.selectByPrimaryKey(id);
        if(message == null)
            return new MyMap().put("code",RECORD_NOT_EXITS).put("msg","record not exits").toMap();
        message.setOperationManager((Integer) map.get("operationId"));
        message.setOperationMsg((String) map.get("msg"));
        message.setState(REPAIR_STATE_REFUSE);
        messageMapper.updateByPrimaryKeySelective(message);
        return new MyMap().put("code",SUCCESS).toMap();
    }

    @Override
    public Map<String, Object> managerRepair(Map<String, Object> map) {
        Integer id = (Integer) map.get("id");
        Message message = messageMapper.selectByPrimaryKey(id);
        if(message == null)
            return new MyMap().put("code",RECORD_NOT_EXITS).put("msg","record not exits").toMap();
        message.setOperationManager((Integer) map.get("operationId"));
        message.setState(REPAIR_STATE_INRUNNING);
        Integer workerId = (Integer) map.get("workerId");
        if(workerId!=null)
            message.setWorkerId(workerId);
        messageMapper.updateByPrimaryKeySelective(message);
        return new MyMap().put("code",SUCCESS).toMap();
    }

    @Override
    public Map<String, Object> searchROHItem(Integer itemId) {
        OtherSearchHORList otherSearchHORList = messageMapper.SearchROHItem(new MyMap().put("itemId",itemId).toMap());
        if(otherSearchHORList == null)
            return new MyMap().put("code", Dictionary.CODE.RECORD_NOT_EXITS).put("msg","record not exist").toMap();
        List<String> imageUrls = new ArrayList<>();
        Example example = new Example(Image.class);
        example.or().andEqualTo("tableIden", Dictionary.TABLE.TABLE_OTHER_QUESTION)
                .andEqualTo("repairid",otherSearchHORList.getId());
        List<Image> images = imageMapper.selectByExample(example);
        for(Image image: images)
            imageUrls.add(image.getUrl());
        otherSearchHORList.setPic(imageUrls);
        return new MyMap().put("code",SUCCESS).put("msg","success").put("data",otherSearchHORList).toMap();
    }

//    @Override
//    public Map<String, Object> addMessage(Map<String, Object> paramMap) {
//        /**
//         * 查询是否有该类别的
//         * 先查询学生
//         * 查询message表，看是否有未读消息，并且今天该宿舍是否已经有人报了
//         *      一天相差 24*60*60*1000;
//         * 有人报修则返回报修人和报修信息
//         * 没有人报修则添加信息
//         */
//        Integer type = (Integer) paramMap.get("type");
//        Integer sid = (Integer) paramMap.get("sid");
//        Map<String,Object> returnMap = new HashMap<>();
//        Otherquestion otherquestion = otherquestionMapper.selectByPrimaryKey(type);
//        if(otherquestion==null){//为了防止用户没有刷新的情况下，管理员删除分类
//            returnMap.put("code", TYPE_ERROR);
//            returnMap.put("data", null);
//            returnMap.put("msg", "不存在该分类");
//            return returnMap;
//        }
//        Student student = studentMapper.selectByPrimaryKey(sid);
//        Example messageExample = new Example(Message.class);
//        Example.Criteria messageCriteria = messageExample.createCriteria();
//        messageCriteria.andEqualTo("studentAddr",student.getStudentAddr());
//        messageCriteria
//                .orEqualTo("isRead",REPAIR_STATE_NO_READ)//未读或则上一次报修在24小时之内
//                .orGreaterThanOrEqualTo("addTime",System.currentTimeMillis()-(24*60*60*1000));
//        List<Message> messageList= messageMapper.selectByExample(messageExample);
//        if(messageList != null && messageList.size()>0) {
//            returnMap.put("code",PREPARE_REPAIR_IS_DECLARE);
//            returnMap.put("data",messageList.get(0));
//            returnMap.put("msg","已存在报修");
//            return returnMap;
//        }
//        Message message = new Message();
//        message.setStudentIdentity(student.getStudentIden());
//        message.setStudentAddr(student.getStudentAddr());
//        message.setQuestionId(type);
//        message.setAddTime(System.currentTimeMillis());
//        message.setIsRead(REPAIR_STATE_NO_READ);
//        messageMapper.insertSelective(message);
//        returnMap.clear();
//        returnMap.put("code",SUCCESS);
//        return returnMap;
//    }
}
